package com.test.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * Created by xingfeng on 19-3-4.
 */
@Slf4j
public class ZKConnectSessionWatcher implements Watcher {
//    final static Logger log = LoggerFactory.getLogger(ZKConnect.class);
    public static final String zkServerPath = "127.0.0.1:2181"; //连接单击
    public static final String zkClusterServerPath = "127.0.0.1:2182,127.0.0.1:2183,,127.0.0.1:2184";//连接集群
    public static final Integer timeout = 5000;

    public static void main(String[] args) throws Exception {
        /**
         * 客户端和zk服务端连接是一个异步的过程，当连接成功之后，客户端会收到一个watch通知
         */
        ZooKeeper zooKeeper = new ZooKeeper(zkServerPath,timeout,new ZKConnectSessionWatcher());

        log.warn("客户端开始连接Zookeeper服务器。。。");
        log.warn("连接状态：{}",zooKeeper.getState());
        new Thread().sleep(2000);   //此处有一定休眠，才可保证能够有时间接收到process的watch
        log.warn("连接状态：{}",zooKeeper.getState());

        long sessionId = zooKeeper.getSessionId();
        byte[] sessionPasswd = zooKeeper.getSessionPasswd();
        log.warn("客户端sessionID:"+sessionId);

        new Thread( ).sleep(200);

        log.warn("开始会话重连。。。");
        ZooKeeper zkSession = new ZooKeeper(zkServerPath,timeout,new ZKConnectSessionWatcher(),sessionId,sessionPasswd);
        log.warn("重连连接状态：{}",zkSession.getState());
        new Thread().sleep(2000);   //此处有一定休眠，才可保证能够有时间接收到process的watch
        log.warn("重连连接状态：{}",zkSession.getState());

        //echo dump | nc localhost 2181     //查看连接效果

        long tmpSessionId = zkSession.getSessionId();
        log.warn("重连客户端sessionID:"+tmpSessionId);
        if(sessionId == tmpSessionId)
            log.warn("sessionID一致："+tmpSessionId);

    }

    public void process(WatchedEvent watchedEvent) {
        log.warn("接收到watch通知:{}",watchedEvent);
    }
}
